package com.example.urmsadmin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.urmsadmin.entity.SysRoleMenu;
import com.example.urmsadmin.entity.SysUserRole;
import com.example.urmsadmin.service.SysRoleMenuService;
import com.example.urmsadmin.service.impl.SysRoleMenuServiceImpl;
import com.example.urmsadmin.vo.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * 角色和菜单关联表(SysRoleMenu)表控制层
 *
 * @author makejava
 * @since 2022-07-12 08:46:11
 */
@RestController
@Slf4j
@RequestMapping(value = "/sysRoleMenu")
public class SysRoleMenuController {

    @Autowired
    private SysRoleMenuService roleMenuService;

    /**
     * @param roleId 角色Id
     * @return
     */
    @GetMapping("/getMenuByRoleId")
    public CommonResult<Object> getMenuByRoleId(@RequestParam String roleId){
        log.info("执行了===>SysRoleMenuController中的getMenuByRoleId方法");
        //查询条件
        QueryWrapper<SysRoleMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id",roleId);
        List<SysRoleMenu> menus = roleMenuService.list(wrapper);
        return new CommonResult<>(200, "success", menus);
    }

    /**
     * @param roleId  类型
     * @param menuIds 操作菜单的id的字符串,以逗号分隔
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @PreAuthorize("@per.hasPermi('system:role:permiSet')")
    @GetMapping("/addMenuToRole/{roleId}")
    public CommonResult<String> addMenuToRole(@PathVariable("roleId") String roleId,String menuIds) {
        log.info("执行了===>SysRoleMenuController中的addMenuToRole方法");
        roleMenuService.removeById(Long.parseLong(roleId));
        if(Objects.equals("",menuIds)){
            return new CommonResult<>(200,"操作成功");
        }
        //转换成数组 需要操作的角色的id数组
        String[] ids = menuIds.split(",");
        StringBuilder resultData = new StringBuilder();
        for(String id : ids){
            SysRoleMenu roleMenu = new SysRoleMenu();
            roleMenu.setRoleId(Long.parseLong(roleId));
            roleMenu.setMenuId(Long.parseLong(id));
            boolean isSave = roleMenuService.save(roleMenu);
            if(!isSave){
                resultData.append("菜单"+id+"设置失败;");
            }
        }
        if("".equals(resultData.toString())){
            return new CommonResult<>(200,"操作成功");
        }
        return new CommonResult<>(233,resultData.toString());
    }
}

